import { message, Modal, ModalFuncProps } from 'ant-design-vue'
import { onUnmounted, ref } from 'vue'
import { useRequest } from 'vue-request'

import { algoDevApi } from '@/services'

type NotebookIdType = string | number | undefined

//(1, "创建中"),(2, "启动中"),(3, "运行中")(5, "停止"),(6, "异常"),
const errorToastStatus = [5, 6]
// 1：notebook  2: 算法
export const useOpenNotebook = (checkType: 1 | 2) => {
  const notebookId = ref<NotebookIdType>()
  const serviceUrl = ref<string | null>()
  let getStatusTimer: any = null
  let warningModal: { destroy: any; update?: (newConfig: ModalFuncProps) => void } | null = null
  const checkApi = checkType === 1 ? algoDevApi.checkNotebookStatus : algoDevApi.checkAlgorithmStatus
  const { runAsync: ruCheckNotebookStatus } = useRequest(checkApi, {
    onSuccess: (data: any) => {
      console.log('data', data)
      const status = checkType === 1 ? data.data : data.data.status
      if (status === 3) {
        if (checkType === 1) {
          window.open(`${serviceUrl.value}`)
        }
        if (checkType === 2 && data.data.serviceUrl) {
          window.open(`${data.data.serviceUrl}`)
        }
        clearModalTimer()
        return
      }
      if (errorToastStatus.includes(status)) {
        message.error('NoteBook启动异常')
        clearModalTimer()
        return
      }
      console.log('6666666666666', getStatusTimer)

      if (!getStatusTimer) {
        timerGetStatus()
      }
    }
  })

  const checkNotebookStatus = async (id: NotebookIdType, url: string | null | undefined) => {
    clearModalTimer()
    if (!id) {
      message.error('NoteBook启动异常')
      return
    }
    notebookId.value = id
    serviceUrl.value = url
    const res = await ruCheckNotebookStatus({}, { urlParams: { id: id } })
    const status = checkType === 1 ? res.data : res.data.status
    if (status < 3) {
      warningModal = Modal.warning({
        title: `正在启动NoteBook环境，大约需要1-2分钟，请您耐心等待`,
        okButtonProps: {
          type: 'default'
        },
        centered: true,
        onOk: () => {
          clearModalTimer()
        }
      })
    }
  }

  // 定时获取状态
  const timerGetStatus = () => {
    getStatusTimer = setInterval(() => {
      ruCheckNotebookStatus({}, { urlParams: { id: notebookId.value } })
    }, 1000)
  }

  // 清除计时器、Modal
  const clearModalTimer = () => {
    if (warningModal) {
      warningModal.destroy()
    }
    clearInterval(getStatusTimer)
    getStatusTimer = null
  }

  onUnmounted(() => {
    clearModalTimer()
  })

  return {
    checkNotebookStatus
  }
}
